package com.test.webchat.Component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class OnlineUserManager {
    public ConcurrentHashMap<Integer, WebSocketSession> map = new ConcurrentHashMap<>();

    // 建立连接并进行存储
    public void online(Integer userId, WebSocketSession webSocketSession) {
        if (map.get(userId) != null) {
            System.out.println("[" + userId + "] 已经被登录了, 登录失败!");
            return;
        }
        map.put(userId, webSocketSession);
        System.out.println("[" + userId + "] 上线!");
    }

    // 关闭连接删除用户信息
    public void offline(Integer userId, WebSocketSession webSocketSession) {
        WebSocketSession existSession = map.get(userId);
        if (existSession == webSocketSession) {
            // 如果这俩 session 是同一个, 才真正进行下线操作
            map.remove((userId));
            System.out.println("[" + userId + "] 下线!");
        }
    }

    // 获取WebSocket
    public WebSocketSession getwebSocketSession(Integer userId){
        return map.get(userId);
    }
}
